package kq

import (
	"context"
	"encoding/json"
	"fmt"
	"strconv"
	"strings"

	"mall/common/globalkey"
	"mall/common/mqueuex"
	"mall/common/utils/pointy"
	"mall/service/backend/common/deepseek"
	"mall/service/backend/rmq/internal/svc"
	"mall/service/blog/rpc/blogclient"
	"mall/service/forum/rpc/forumclient"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

/**
 * Listening to the payment flow status change notification message queue
 */
type DeferredCreateGorseItemMq struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewDeferredCreateGorseItemMq(ctx context.Context, svcCtx *svc.ServiceContext) *DeferredCreateGorseItemMq {
	return &DeferredCreateGorseItemMq{
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *DeferredCreateGorseItemMq) Consume(_, val string) error {
	fmt.Println("DeferredCreateGorseItemMq Consume......000000")
	// 解析数据
	var message mqueuex.DeferredCreateGorseItemMessage
	if err := json.Unmarshal([]byte(val), &message); err != nil {
		// logx.WithContext(l.ctx).Error("DeferredCreateGorseItemMq.Consume Unmarshal err : %v , val : %s", err, val)
		logx.Errorw("DeferredCreateGorseItemMq.Consume json.Unmarshal err", logx.Field("detail", err.Error()))
		return err
	}

	// 执行业务..
	if err := l.execService(&message); err != nil {
		// logx.WithContext(l.ctx).Error("DeferredCreateGorseItemMq.execService err : %v , val : %s , message: %+v", err, val, message)
		logx.Errorw("DeferredCreateGorseItemMq.execService err", logx.Field("detail", err.Error()),
			logx.Field("val", val), logx.Field("message", fmt.Sprintf("%+v", message)))
		return err
	}

	return nil
}

// Verify and update relevant flow data
func (l *DeferredCreateGorseItemMq) execService(message *mqueuex.DeferredCreateGorseItemMessage) error {
	fmt.Println("DeferredCreateGorseItemMq message", message)
	if message.Ids == nil || message.ContentType == nil {
		return errors.New(fmt.Sprintf("DeferredCreateGorseItemMq.execService err. Failed to update cart due to invalid param: %+v", message))
	}
	ids := strings.Split(*message.Ids, ",")
	cType := *message.ContentType
	var platformId uint32 = globalkey.ThirdPartyPlatformWechatMini
	if cType == globalkey.AttachmentLogTypePost {
		preload := "blogPost:Id"
		eagerLoad := "blogPost:blogPostDetail"
		preload += ";blogPostDetail:ContentHtml"
		var filters []string
		filters = append(filters, "Status,equalTo:"+strconv.FormatInt(int64(globalkey.PostStatusPublish), 10))
		for _, v := range ids {
			id, err := strconv.ParseUint(v, 10, 64)
			if err != nil {
				logx.Errorf("DeferredCreateGorseItemMq.Consume execService ParseUint err: %+v,Please try again,blogPostId: %+v", err, v)
				continue
			}
			post, err := l.svcCtx.BlogRpc.GetPostById(l.ctx, &blogclient.BaseIdReq{
				Id:         pointy.GetPointer(id),
				Preload:    pointy.GetPointer(preload),
				EagerLoad:  pointy.GetPointer(eagerLoad),
				Filter:     pointy.GetPointer(strings.Join(filters, ";")),
				PlatformId: pointy.GetPointer(platformId),
			})
			// logrus.Info(fmt.Sprintf("DeferredCreateGorseItemMq execService order: %+v", order))
			if err != nil {
				logx.Errorf("DeferredCreateGorseItemMq.Consume execService ParseUint err: %+v,Please try again,blogPostId: %+v", err, v)
				continue
			}
			var label []string
			if post.Content != nil && len(strings.TrimSpace(*post.Content)) > 0 {
				label = deepseek.GetContentLabel(*post.Content)
			}
			if len(label) > 0 && post.Id != nil && *post.Id > 0 {
				err := l.createItemLogic(globalkey.GorseBLogPostPrefix+strconv.FormatUint(*post.Id, 10), label)
				if err != nil {
					logx.Errorf("DeferredCreateGorseItemMq.Consume execService createItemLogic err: %+v,Please try again,blogPostId: %+v", err, v)
					continue
				}
			} else {
				logx.Errorf("DeferredCreateGorseItemMq.Consume execService err: label or id is empry,Please try again,blogPostId: %+v", v)
			}
		}
	}

	if cType == globalkey.AttachmentLogTypeForumPost {
		var preload string = "forumPost:Id,ContentHtml"
		var eagerLoad string = "forumPost:"
		var filters []string
		filters = append(filters, "Status,equalTo:"+strconv.FormatInt(int64(globalkey.PostStatusPublish), 10))
		for _, v := range ids {
			id, err := strconv.ParseUint(v, 10, 64)
			if err != nil {
				logx.Errorf("DeferredCreateGorseItemMq.Consume execService ParseUint err: %+v,Please try again,forumPostId: %+v", err, v)
				continue
			}
			post, err := l.svcCtx.ForumRpc.GetPostById(l.ctx, &forumclient.BaseIdReq{
				Id:         pointy.GetPointer(id),
				Preload:    pointy.GetPointer(preload),
				EagerLoad:  pointy.GetPointer(eagerLoad),
				Filter:     pointy.GetPointer(strings.Join(filters, ";")),
				PlatformId: pointy.GetPointer(platformId),
			})
			// logrus.Info(fmt.Sprintf("DeferredCreateGorseItemMq execService order: %+v", order))
			if err != nil {
				logx.Errorf("DeferredCreateGorseItemMq.Consume execService ParseUint err: %+v,Please try again,forumPostId: %+v", err, v)
				continue
			}
			var label []string
			if post.Content != nil && len(strings.TrimSpace(*post.Content)) > 0 {
				label = deepseek.GetContentLabel(*post.Content)
			}
			if len(label) > 0 && post.Id != nil && *post.Id > 0 {
				err := l.createItemLogic(globalkey.GorseForumPostPrefix+strconv.FormatUint(*post.Id, 10), label)
				if err != nil {
					logx.Errorf("DeferredCreateGorseItemMq.Consume execService createItemLogic err: %+v,Please try again,forumPostId: %+v", err, v)
					continue
				}
			} else {
				logx.Errorf("DeferredCreateGorseItemMq.Consume execService err: label or id is empry,Please try again,forumPostId: %+v", v)
			}
		}
	}

	if cType == globalkey.AttachmentLogTypeKnowledgeBase {
		preload := "blogBook:Id,SectionId"
		eagerLoad := "blogBook:blogBookDetail,blogBookMeta,blogBookRelation,blogTerm"
		preload += ";blogBookDetail:ContentHtml"
		preload += ";blogBookMeta:year,gender"
		preload += ";blogBookRelation:brand,nose,note"
		preload += ";blogTerm:Id,Name,Slug"
		filters := []string{"Status,equalTo:" + strconv.FormatInt(int64(globalkey.PostStatusPublish), 10)}
		var platformId uint32 = globalkey.ThirdPartyPlatformWechatMini
		for _, v := range ids {
			id, err := strconv.ParseUint(v, 10, 64)
			if err != nil {
				logx.Errorf("DeferredCreateGorseItemMq.Consume execService ParseUint err: %+v,Please try again,forumPostId: %+v", err, v)
				continue
			}
			post, err := l.svcCtx.BlogRpc.GetKBPostById(l.ctx, &blogclient.BaseIdReq{
				Id:         pointy.GetPointer(id),
				Preload:    pointy.GetPointer(preload),
				EagerLoad:  pointy.GetPointer(eagerLoad),
				Filter:     pointy.GetPointer(strings.Join(filters, ";")),
				PlatformId: pointy.GetPointer(platformId),
			})
			// logrus.Info(fmt.Sprintf("DeferredCreateGorseItemMq execService order: %+v", order))
			if err != nil {
				logx.Errorf("DeferredCreateGorseItemMq.Consume execService ParseUint err: %+v,Please try again,entryId: %+v", err, id)
				continue
			}

			var label []string
			var category []string
			if post.Content != nil && len(strings.TrimSpace(*post.Content)) > 0 {
				label = deepseek.GetContentLabel(*post.Content)
			}

			//香水的品牌、气味、调香师、年份、性别作为分类
			if len(post.Relations) > 0 {
				for _, rel := range post.Relations {
					if rel.Title != nil && len(strings.TrimSpace(*rel.Title)) > 0 {
						category = append(category, *rel.Title)
					}
				}
			}
			if len(post.Meta) > 0 {
				for _, m := range post.Meta {
					if len(strings.TrimSpace(*m.Value)) > 0 {
						category = append(category, *m.Value)
					}
				}
			}

			if len(label) > 0 && post.Id != nil && *post.Id > 0 {
				err := l.createItemLogic(globalkey.GorseKnowledgeBasePrefix+strconv.FormatUint(*post.Id, 10), label)
				if err != nil {
					logx.Errorf("DeferredCreateGorseItemMq.Consume execService createItemLogic err: %+v,Please try again,entryId: %+v", err, v)
					continue
				}
			} else {
				logx.Errorf("DeferredCreateGorseItemMq.Consume execService err: label or id is empry,Please try again,entryId: %+v", v)
			}
		}
	}

	return nil
}

func (l *DeferredCreateGorseItemMq) createItemLogic(pid string, labels []string) error {
	return l.svcCtx.GorseClient.CreateItem(
		l.svcCtx.Config.Query.GorseUrl,
		pid, "", "1",
		labels, strings.Split(strconv.FormatInt(int64(globalkey.AttachmentLogKbEntry), 10), ","),
	)
}
